package com.yinkgh.mybatis.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yinkgh.datasource.DataSource;
import com.yinkgh.datasource.DataSourceType;
import com.yinkgh.mybatis.common.service.BaseService;
import com.yinkgh.mybatis.common.service.impl.BaseServiceImpl;
import com.yinkgh.mybatis.dao.UserMapper;
import com.yinkgh.mybatis.model.Company;
import com.yinkgh.mybatis.model.Employee;
import com.yinkgh.mybatis.model.User;
import com.yinkgh.mybatis.view.UserView;
import com.yinkgh.util.BeanCopyUtil;

/**
 * 本类讲解事物的配置以及使用
 * 基于注解的多数据源的用法
 * @author yinkgh
 *
 */
@Transactional(readOnly=true)
@DataSource(DataSourceType.DATASOURCEB)
//@DataSource(DataSourceType.DATASOURCEA)
@Service
public class UserService extends BaseServiceImpl<User> {
	
	@Autowired
	UserMapper userDao;
	
	@Autowired
	EmployeeService employeeService;
	
	@Autowired
	CompanyService companyService;

	@Override
	public UserMapper getDao() {
		return userDao;
	}
	
	@DataSource(DataSourceType.DATASOURCEA)
	@Transactional(readOnly=false)
	public int insert(User record, Employee employee) {
		int result2 = super.insert(record);
		int result = employeeService.addEmployee(employee);
		Company company = new Company();
		company.setAddress("2234");
		company.setName("昌平");
		companyService.insert(company);
//		int a = 1 / 0;
		List<User> list = new ArrayList<User>();
//		list.get(0);
		if (result > 0 && result2 > 0) {
			return result + result2;
		}
		return 0;
	}
	
	@DataSource(DataSourceType.DATASOURCEA)
	@Transactional(readOnly=false)
	public int insertA(UserView userView) {
		User dest = new User();
		try {
			BeanCopyUtil.copyProperties(dest, userView);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return userDao.insert(dest);
	}
	
	@DataSource(DataSourceType.DATASOURCEB)
	@Transactional(readOnly=false)
	public int insertB(UserView userView) {
		User dest = new User();
		try {
			BeanCopyUtil.copyProperties(dest, userView);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return userDao.insert(dest);
	}
	
	
	@Transactional(readOnly=false)
	public int insertBatch(List<User> users) {
		return insertBatch(users);
	}
}
